#-*- coding utf-8 -*-
import time
import hashlib
import requests
import json
import datetime

def formatGMTime():
    GMT_FORMAT =  '%a, %d %b %Y %H:%M:%S GMT'
    return datetime.datetime.utcnow().strftime(GMT_FORMAT)

class OSSClient(object):
    def __init__(self, app_domain, auth_domain, app_id, app_key, bucket):
        assert app_domain is not None and app_domain.strip() != "", "app_domain 不能为空"
        assert auth_domain is not None and auth_domain.strip() != "", "auth_domain 不能为空"
        assert app_id is not None and app_id.strip() != "", "app_id 不能为空"
        assert app_key is not None and app_key.strip() != "", "app_key 不能为空"
        assert bucket is not None and bucket.strip() != "", "bucket不能为空"
        self.app_domain = app_domain
        self.auth_domain = auth_domain
        self.app_id = app_id
        self.app_key = app_key
        self.bucket = bucket


    def createCert(self):
        ts = str(int(time.time()))
        signature_str = self.app_id + ts + self.app_key
        signature = hashlib.md5(signature_str.encode('utf-8')).hexdigest()
        params = {
            'appid': self.app_id,
            'ts': ts,
            'signature': signature
        }
        url = self.app_domain + "/v1/appmanager/certification/create"
        r = requests.post(url=url, data=json.dumps(params))
        res = json.loads(r.text)
        if res["code"] == 200:
            return res["data"]["certification"]
        else:
            raise AssertionError(res["msg"])

    def upload(self, object_name, object_path):
        cert = self.createCert()
        headers = {
            'Content-Type': 'binary/octet-stream',
            'Certification': cert,
            'x-amz-date': formatGMTime(),
            'x-amz-acl': 'public-read-write',
        }

        url = self.auth_domain + "/v1/oss/object/upload/" + self.app_id + "/" + self.bucket + "/" + object_name
        with open(object_path, 'rb') as f:
            data = f.read()
            r = requests.put(url, data=data, headers=headers)
            print(r.text)
            if r.reason != 'OK':
                raise AssertionError(r.reason)

    def download(self, object_name, download_path):
        cert = self.createCert()
        headers = {
            "x-amz-date": formatGMTime(),
            "Certification": cert,
        }
        url = self.auth_domain + "/v1/oss/object/download/" + self.app_id + "/" + self.bucket + "/" + object_name
        r = requests.get(url, headers=headers)
        if r.reason == 'OK':
            with open(download_path, "wb") as f:
                f.write(r.content)
        else:
            raise AssertionError(r.reason)

    def getPresignedUrl(self, object_name):
        cert = self.createCert()
        params = {
            "appid": self.app_id,
            "bucket": self.bucket,
            "object": object_name,
            "acl": 'public-read-write',
            "expire": -1,
            "certification": cert
        }
        url = self.app_domain + "/v1/appmanager/object/get_presignedurl"
        r = requests.post(url=url, data=json.dumps(params))
        if r.reason == 'OK':
            res = json.loads(r.text)
            url = res["data"]["url"]
            return url
        else:
            raise AssertionError(r.reason)

if __name__ == "__main__":
    oss_client = OSSClient(app_domain='http://meicloud.com:80',
                           auth_domain='http://meicloud.com:17480',
                           app_id='C69466847E9846FA840599350738002C',
                           app_key='AU6ctrVpVkeSfYMoEFRxfENG1wJa49s2muoi5IvL',
                           bucket='meicloud-ai-paltfrom');
    oss_client.upload("test.csv", "D:/算法平台/code/boston_Regression.csv")